package com.dabai.simpleconnection_udp;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.PopupMenu;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.animation.ScaleInAnimation;
import com.dabai.simpleconnection_udp.adapter.MyViewPagerAdapter;
import com.dabai.simpleconnection_udp.adapter.UdpAdapter;
import com.dabai.simpleconnection_udp.adapter.UdpMsgAdapter;
import com.dabai.simpleconnection_udp.base.BaseAlertDialogBuilder;
import com.dabai.simpleconnection_udp.bean.UdpCommandModel;
import com.dabai.simpleconnection_udp.bean.UdpMsgModel;
import com.dabai.simpleconnection_udp.db.SQLiteDatabaseHelper;
import com.dabai.simpleconnection_udp.db.SQLiteDatabaseHelper2;
import com.dabai.simpleconnection_udp.log.LogTagEnum;
import com.dabai.simpleconnection_udp.log.LogUtils;
import com.dabai.simpleconnection_udp.ui.SettingsActivity;
import com.dabai.simpleconnection_udp.utils.DabaiUtils;
import com.dabai.simpleconnection_udp.utils.DateUtils;
import com.dabai.simpleconnection_udp.utils.DisplayUtils;
import com.dabai.simpleconnection_udp.utils.IPUtils;
import com.dabai.simpleconnection_udp.utils.MdcDialog;
import com.dabai.simpleconnection_udp.utils.NetWorkUtils;
import com.dabai.simpleconnection_udp.utils.NotificationUtils;
import com.dabai.simpleconnection_udp.utils.StringUtils;
import com.dabai.simpleconnection_udp.utils.UDPManager2;
import com.dabai.simpleconnection_udp.utils.ViewUtils;
import com.dabai.simpleconnection_udp.utils.charset.CharsetUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.chip.Chip;
import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton;
import com.google.android.material.textfield.TextInputLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import es.dmoral.toasty.Toasty;


/**
 * 主要活动
 * 请欣赏我的shi山代码
 * 一页千行
 *
 * @author Flower3
 * @date 2023/08/30
 */
public class MainActivity extends AppCompatActivity {


    Context context;
    private TextView mIpaddress1;
    private TextView mIpaddress2;
    private RecyclerView mRecyclerview1;
    private RecyclerView mRecyclerview2;
    private BottomNavigationView mBottomNavigation;
    private ExtendedFloatingActionButton mFloatingActionButton1;
    private ExtendedFloatingActionButton mFloatingActionButton2;
    SQLiteDatabase db;
    private UdpAdapter udpAdapter;
    private UdpMsgAdapter udpMsgAdapter;
    private final String TAG = "DBTAG";


    private ViewPager viewPager;

    private List<View> viewList;
    private View page1_root_view;
    private View page2_root_view;


    private String defaultLast;
    private TextView defaultTextPort;
    private TextView defaultTextIp;
    private TextView defaultTextContent;
    private Chip defaultMode;
    private UDPManager2 defaultSendUdpManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        context = this;
        //初始化 log系统
        LogUtils.init(getExternalCacheDir().getPath() + "/app_log.log");

        initViewPagerAndBottomNav();

        initDB();

        initOtherViews();

        arrayList = new ArrayList<>();
        arrayList2 = new ArrayList<>();
        refreshData();
        refreshData2();
        getIp();

        setFloatButtonClickListener();

        initDefaultSendUdpListen(false);


    }


    private void initDefaultSendUdpListen(boolean isRandom) {

        CardView cardView = page2_root_view.findViewById(R.id.defaultCard);
        defaultMode.setOnClickListener(v -> initDefaultSendUdpListen(true));
        mIpaddress1.setOnClickListener(v -> initDefaultSendUdpListen(true));
        cardView.setOnClickListener(v -> {
            View diaView = ViewUtils.inflateLayout(context, R.layout.dialog_log);
            TextView textView1 = diaView.findViewById(R.id.appLogTextView);


            ScrollView scrollView = diaView.findViewById(R.id.logScroll);

            new BaseAlertDialogBuilder(context)
                    .setTitle("历史记录")
                    .setView(diaView)
                    .setPositiveButton("确认", null)
                    .show();

            new Thread(() -> {

                runOnUiThread(() -> {
                    textView1.setText(defaultLast);
                    // 将ScrollView滚动到底部
                    scrollView.post(() -> scrollView.fullScroll(View.FOCUS_DOWN));
                });

            }).start();
        });


        int randomNumber = isRandom ? new Random().nextInt(12310 - 12300 + 1) + 12300 : 12306;
        try {

            defaultSendUdpManager = new UDPManager2();
            defaultSendUdpManager.initListen(randomNumber);

            mIpaddress1.setText("默认发信端口:" + randomNumber);
            defaultTextPort.setText(String.valueOf(randomNumber));
            defaultMode.setText("监听中");

            defaultLast = "";

            new Thread(() -> {

                while (true) {
                    defaultSendUdpManager.recvMsg(listenPacket -> runOnUiThread(() -> {

                        String ipAndPort = listenPacket.getAddress().toString().replace("/", "") + ":" + listenPacket.getPort();
                        //  udpMsgModel.setIp("来自 " + ipAndPort + " 的消息");

                        //todo 编码处理

                        byte[] data = listenPacket.getData();

                        String msg_text = new String(data, 0, listenPacket.getLength());

                        defaultLast = defaultLast + "\n[" + DateUtils.getNowTime(1) + "] " + "[" + CharsetUtils.getCharset(data) + "]" + ipAndPort + "\n" + msg_text + "\n";

                        defaultTextIp.setText(ipAndPort);
                        defaultTextContent.setText(msg_text);

                        NotificationUtils.notificationText(context,
                                "默认监听端口", "默认监听端口", R.drawable.ic_stat_msg,
                                "默认端口接收到" + ipAndPort + "的信息", msg_text);

                    }));
                }
            }).start();

        } catch (Exception e) {
            mIpaddress1.setText("默认端口冲突:" + randomNumber);
            defaultTextPort.setText(String.valueOf(randomNumber));
            defaultMode.setText("默认端口冲突");
            e.printStackTrace();
        }
    }


    /**
     * 设置浮动按钮单击侦听器
     */
    private void setFloatButtonClickListener() {
        mFloatingActionButton1.setOnClickListener(v -> {

            //todo 添加
            View dia_view = ViewUtils.inflateLayout(context, R.layout.dialog_add_udp);

            TextInputLayout til1 = dia_view.findViewById(R.id.til1);
            TextInputLayout til2 = dia_view.findViewById(R.id.til2);
            TextInputLayout til3 = dia_view.findViewById(R.id.til3);
            TextInputLayout til4 = dia_view.findViewById(R.id.til4);
            TextInputLayout til5 = dia_view.findViewById(R.id.til5);

            Button button1 = dia_view.findViewById(R.id.outlinedButton1);

            button1.setOnClickListener(v1 -> {
                ViewUtils.setTextInputLayoutText(til2, "255.255.255.255");
                ViewUtils.setTextInputLayoutText(til5, "广播类型信息");
            });


            AlertDialog addDia = new BaseAlertDialogBuilder(context)
                    .setTitle("新建UDP命令")
                    .setView(dia_view)
                    .setNeutralButton("取消", null)
                    .setPositiveButton("添加", null).show();

            addDia.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(v12 -> {

                String name = ViewUtils.getTextInputLayoutText(til1);
                String ip = ViewUtils.getTextInputLayoutText(til2);
                String port = ViewUtils.getTextInputLayoutText(til3);
                String content = ViewUtils.getTextInputLayoutText(til4);
                String note = ViewUtils.getTextInputLayoutText(til5);

                //非法检测
                if (StringUtils.containsEmpty(name, ip, port, content)) {
                    DabaiUtils.showDialog(context, "各项不能为空");
                    return;
                }
                if (!IPUtils.isIP(ip)) {
                    DabaiUtils.showDialog(context, "非法IP地址");
                    return;
                }
                if (!IPUtils.isPort(port)) {
                    DabaiUtils.showDialog(context, "非法端口");
                    return;
                }


                UdpCommandModel udpCommandModel = new UdpCommandModel(name, note, ip, Integer.parseInt(port), content);

                long id = SQLiteDatabaseHelper.insertData(db, udpCommandModel);
                udpCommandModel.setId((int) id);

                if (id != -1) {

                    udpAdapter.addData(udpCommandModel);
                    udpAdapter.notifyItemInserted(udpAdapter.getItemCount());

                    Toasty.success(this, "添加成功", Toast.LENGTH_SHORT, true).show();

                    // 将ScrollView滚动到底部
                    mRecyclerview1.post(() -> mRecyclerview1.smoothScrollToPosition(udpAdapter.getItemCount() - 1));

                } else {
                    Toasty.error(this, "添加失败", Toast.LENGTH_SHORT, true).show();
                }

                LogUtils.appendLog(LogTagEnum.TAG_CMD_ADD, udpCommandModel.toString());
                addDia.dismiss();

            });

        });

        mFloatingActionButton2.setOnClickListener(v -> {
            //todo 新建监听端口
            MdcDialog.showInputDialog2(context, "新建监听端口", "", "", "请输入标题", "请输入监听端口", new MdcDialog.OnInputDialog2ButtonListener() {
                @Override
                public void confirm(AlertDialog dialog, String content1, String content2) {
                    if (content1.isEmpty()) {
                        DabaiUtils.showDialog(context, "标题为空");
                        return;
                    }
                    if (IPUtils.isPort(content2)) {

                        UdpMsgModel udpMsgModel = new UdpMsgModel(content1, "-", "", "未检测到IP", "未监听到信息", true, Integer.parseInt(content2));

                        long id = SQLiteDatabaseHelper2.insertData(db, udpMsgModel);
                        udpMsgModel.setId((int) id);

                        if (id != -1) {

                            udpMsgAdapter.addData(udpMsgModel);
                            udpMsgAdapter.notifyItemInserted(udpMsgAdapter.getItemCount());

                            Toasty.success(context, "添加成功", Toast.LENGTH_SHORT, true).show();

                            startListen(udpMsgModel);


                            // 将ScrollView滚动到底部
                            mRecyclerview2.post(() -> mRecyclerview2.smoothScrollToPosition(udpMsgAdapter.getItemCount() - 1));

                        } else {
                            Toasty.error(context, "添加失败", Toast.LENGTH_SHORT, true).show();
                        }

                        LogUtils.appendLog(LogTagEnum.TAG_CMD_ADD, udpMsgModel.toString());

                        dialog.dismiss();
                    } else {
                        DabaiUtils.showDialog(context, "非法端口");
                    }
                }

                @Override
                public void cancel() {

                }
            }).show();
        });

    }

    /**
     * 初始化数据库
     */
    private void initDB() {
        //todo 初始化数据库
        db = openOrCreateDatabase("UDPSet", Context.MODE_PRIVATE, null);
        String create = "create table if not exists UDPSet(id integer primary key autoincrement,name text not null,note text not null,ip text not null,port integer not null,content text not null);";
        db.execSQL(create);

        String create2 = "create table if not exists UDPRecv(id integer primary key autoincrement,name text not null,note text not null,port integer not null UNIQUE,last text not null);";
        db.execSQL(create2);
    }

    /**
     * 初始视图寻呼机和底部导航
     */
    private void initViewPagerAndBottomNav() {
        viewPager = findViewById(R.id.viewPager);
        mBottomNavigation = findViewById(R.id.bottom_navigation);

        initViewPagerData();
        MyViewPagerAdapter myViewPagerAdapter = new MyViewPagerAdapter(viewList);
        viewPager.setAdapter(myViewPagerAdapter);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mBottomNavigation.getMenu().getItem(position).setChecked(true);
                setFloatButtonVisibility();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mBottomNavigation.setOnItemSelectedListener(item -> {
            viewPager.setCurrentItem(item.getOrder());
            return true;
        });
    }

    /**
     * 初始视图寻呼机数据
     */
    private void initViewPagerData() {

        page1_root_view = ViewUtils.inflateLayout(context, R.layout.view_page_1);
        page2_root_view = ViewUtils.inflateLayout(context, R.layout.view_page_2);

        viewList = new ArrayList<>();
        viewList.add(page1_root_view);
        viewList.add(page2_root_view);

    }

    @Override
    protected void onDestroy() {
        defaultSendUdpManager.close();
        super.onDestroy();
    }


    /**
     * 获取ip
     */
    @SuppressLint("SetTextI18n")
    private void getIp() {

        var ip = NetWorkUtils.getLocalIpAddress(context);
        mIpaddress2.setText("当前设备IP : " + ip);
        LogUtils.appendLog(LogTagEnum.TAG_TAG_OTHER, "当前环境SDK:" + Build.VERSION.SDK_INT + "\nAndroid版本:" + Build.VERSION.RELEASE);

        if (ip.equals("0.0.0.0")) {
            Toasty.error(this, "IP获取失败，请检查网络环境", Toast.LENGTH_SHORT, true).show();
            LogUtils.appendLog(LogTagEnum.TAG_TAG_OTHER, "获取 本机IP:异常:" + ip);
        } else {
            LogUtils.appendLog(LogTagEnum.TAG_TAG_OTHER, "获取 本机IP:" + ip);
        }

    }


    ArrayList<UdpCommandModel> arrayList;

    /**
     * 刷新数据
     */
    private void refreshData() {

        viewWidthAuto();

        //查询语句
        // String search = "select * from graphicsCard where price = "+price;
        String search = "select * from UDPSet";
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery(search, null);
        // cursor.close();

        arrayList.clear();

        while (cursor.moveToNext()) {
            @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex("id"));
            @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("name"));
            @SuppressLint("Range") String content = cursor.getString(cursor.getColumnIndex("content"));
            @SuppressLint("Range") String ip = cursor.getString(cursor.getColumnIndex("ip"));
            @SuppressLint("Range") int port = cursor.getInt(cursor.getColumnIndex("port"));
            @SuppressLint("Range") String note = cursor.getString(cursor.getColumnIndex("note"));

            arrayList.add(new UdpCommandModel(id, name, note, ip, port, content));

        }

        //  cursor.close();
        LogUtils.appendLog(LogTagEnum.TAG_TAG_OTHER, "刷新数据条目:" + arrayList.size());


        //准备适配器
        udpAdapter = new UdpAdapter(arrayList);
        udpAdapter.setAdapterAnimation(new ScaleInAnimation());
        udpAdapter.setOnItemClickListener((adapter, view, position) -> {
            UdpCommandModel udpCommandModel = arrayList.get(position);

            new BaseAlertDialogBuilder(context)
                    .setTitle("发送命令")
                    .setMessage(StringUtils.inputLine(
                            "ID：" + udpCommandModel.getId(),
                            "名称：" + udpCommandModel.getName(),
                            "目标IP：" + udpCommandModel.getIp(),
                            "目标端口：" + udpCommandModel.getPort(),
                            "",
                            "命令：" + udpCommandModel.getContent(),
                            "",
                            "备注：" + udpCommandModel.getNote()
                    ))
                    .setNeutralButton("取消", null)
                    .setPositiveButton("发送", (dialog, which) -> sendMsg(udpCommandModel))
                    .show();

        });

        udpAdapter.setOnItemLongClickListener((adapter, view, position) -> {

            UdpCommandModel udpCommandModel = arrayList.get(position);
            showClickLongPop(context, view, udpCommandModel, position);

            return true;
        });

        //设置适配器
        mRecyclerview1.setAdapter(udpAdapter);

        udpAdapter.setEmptyView(R.layout.empty_view);

    }


    ArrayList<UdpMsgModel> arrayList2;

    /**
     * 刷新数据
     */
    private void refreshData2() {

        //todo 获取数据库的监听数据

        viewWidthAuto2();

        String search = "select * from UDPRecv";
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery(search, null);

        arrayList2.clear();

        while (cursor.moveToNext()) {
            @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex("id"));
            @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("name"));
            @SuppressLint("Range") String content = "未监听到信息";
            @SuppressLint("Range") String ip = "未检测到IP";
            @SuppressLint("Range") int port = cursor.getInt(cursor.getColumnIndex("port"));
            @SuppressLint("Range") String note = cursor.getString(cursor.getColumnIndex("note"));
            @SuppressLint("Range") String last = cursor.getString(cursor.getColumnIndex("last"));

            arrayList2.add(new UdpMsgModel(id, name, note, last, ip, content, true, port));
        }

        //  cursor.close();
        LogUtils.appendLog(LogTagEnum.TAG_TAG_OTHER, "监听 - 刷新数据条目:" + arrayList2.size());

        //准备适配器
        udpMsgAdapter = new UdpMsgAdapter(arrayList2);
        udpMsgAdapter.setAdapterAnimation(new ScaleInAnimation());
        udpMsgAdapter.setOnItemClickListener((adapter, view, position) -> {
            UdpMsgModel udpMsgModel = arrayList2.get(position);

            View diaView = ViewUtils.inflateLayout(context, R.layout.dialog_log);
            TextView textView1 = diaView.findViewById(R.id.appLogTextView);


            ScrollView scrollView = diaView.findViewById(R.id.logScroll);

            new BaseAlertDialogBuilder(context)
                    .setTitle("历史记录")
                    .setView(diaView)
                    .setPositiveButton("确认", null)
                    .show();

            new Thread(() -> {

                String text = udpMsgModel.getLast();

                runOnUiThread(() -> {
                    textView1.setText(text);
                    // 将ScrollView滚动到底部
                    scrollView.post(() -> scrollView.fullScroll(View.FOCUS_DOWN));
                });

            }).start();

        });

        udpMsgAdapter.setOnItemLongClickListener((adapter, view, position) -> {

            new BaseAlertDialogBuilder(context)
                    .setTitle("提示")
                    .setMessage("确定要删除嘛？")
                    .setPositiveButton("确认", (dialog, which) -> {

                        UdpMsgModel udpMsgModel = arrayList2.get(position);
                        SQLiteDatabaseHelper2.delById(db, udpMsgModel.getId());

                        adapter.removeAt(position);
                        adapter.notifyItemRemoved(position);

                    }).setNeutralButton("取消", null)
                    .show();

            return true;
        });

        //设置适配器
        mRecyclerview2.setAdapter(udpMsgAdapter);
        udpMsgAdapter.setEmptyView(R.layout.empty_view);

        //todo 循环建立端口
        for (int i = 0; i < arrayList2.size(); i++) {

            UdpMsgModel udpMsgModel = udpMsgAdapter.getItem(i);
            startListen(udpMsgModel);

        }
    }


    private void startListen(UdpMsgModel udpMsgModel) {
        try {
            UDPManager2 udpManager2 = new UDPManager2();
            udpManager2.initListen(udpMsgModel.getPort());

            new Thread(() -> {

                while (true) {
                    udpManager2.recvMsg(listenPacket -> runOnUiThread(() -> {

                        String ipAndPort = listenPacket.getAddress().toString().replace("/", "") + ":" + listenPacket.getPort();
                        udpMsgModel.setIp("来自 " + ipAndPort + " 的消息");

                        //todo 编码处理
                        byte[] data = listenPacket.getData();

                        String msg_text = new String(data, 0, listenPacket.getLength());

                        String last = udpMsgModel.getLast() + "\n[" + DateUtils.getNowTime(1) + "] " + "[" + CharsetUtils.getCharset(data) + "]" + ipAndPort + "\n" + msg_text + "\n";
                        udpMsgModel.setLast(last);

                        udpMsgModel.setContent(msg_text);

                        udpMsgAdapter.setData(udpMsgAdapter.getItemPosition(udpMsgModel), udpMsgModel);
                        udpMsgAdapter.notifyItemChanged(udpMsgAdapter.getItemPosition(udpMsgModel));

                        NotificationUtils.notificationText(context,
                                "自定义监听端口", "自定义监听端口", R.drawable.ic_stat_msg,
                                udpMsgModel.getPort() + "端口接收到" + ipAndPort + "的信息", msg_text);

                        SQLiteDatabaseHelper2.updateById(db, udpMsgModel.getId(), udpMsgModel);

                        // 将ScrollView滚动到底部
                        mRecyclerview2.post(() -> mRecyclerview2.smoothScrollToPosition(udpMsgAdapter.getItemPosition(udpMsgModel)));

                    }));
                }
            }).start();
            LogUtils.appendLog(LogTagEnum.TAG_TAG_OTHER, "端口监听成功", udpMsgModel.getPort());

        } catch (Exception e) {
            LogUtils.appendLog(LogTagEnum.TAG_TAG_OTHER, "端口禁止访问", udpMsgModel.getPort());

            udpMsgModel.setMode(false);
            udpMsgAdapter.setData(udpMsgAdapter.getItemPosition(udpMsgModel), udpMsgModel);
            udpMsgAdapter.notifyItemChanged(udpMsgAdapter.getItemPosition(udpMsgModel));

        }
    }


    /**
     * 视图宽度自动
     */
    private void viewWidthAuto() {

        int dp = DisplayUtils.px2dip(context, DisplayUtils.getScreenRealWidth(context));

        if (dp > 1500) {
            //不知道什么鬼东西了  哪有这么大的屏幕
            mRecyclerview1.setLayoutManager(new GridLayoutManager(this, 10));
        } else if (dp > 1000) {
            //平板横屏
            mRecyclerview1.setLayoutManager(new GridLayoutManager(this, 6));
        } else if (dp > 700) {
            //平板竖屏
            mRecyclerview1.setLayoutManager(new GridLayoutManager(this, 4));
        } else if (dp > 500) {
            //手机横屏
            mRecyclerview1.setLayoutManager(new GridLayoutManager(this, 3));
        } else {
            //默认
            mRecyclerview1.setLayoutManager(new GridLayoutManager(this, 2));
        }

    }


    /**
     * 视图宽度自动
     */
    private void viewWidthAuto2() {

        int dp = DisplayUtils.px2dip(context, DisplayUtils.getScreenRealWidth(context));

        if (dp > 1500) {
            //不知道什么鬼东西了  哪有这么大的屏幕
            mRecyclerview2.setLayoutManager(new GridLayoutManager(this, 4));
        } else if (dp > 1000) {
            //平板横屏
            mRecyclerview2.setLayoutManager(new GridLayoutManager(this, 2));
        } else if (dp > 700) {
            //平板竖屏
            mRecyclerview2.setLayoutManager(new GridLayoutManager(this, 2));
        } else if (dp > 500) {
            //手机横屏
            mRecyclerview2.setLayoutManager(new GridLayoutManager(this, 2));
        } else {
            //默认
            mRecyclerview2.setLayoutManager(new GridLayoutManager(this, 1));
        }

    }

    /**
     * 显示点击长弹出
     *
     * @param context         上下文
     * @param udpCommandModel udp命令模型
     */
    private void showClickLongPop(Context context, View showView, UdpCommandModel udpCommandModel, int position) {

        PopupMenu popupMenu = new PopupMenu(context, showView);
        MenuInflater inflater = popupMenu.getMenuInflater();
        inflater.inflate(R.menu.cmd_long_click_pop, popupMenu.getMenu());
        popupMenu.show();

        popupMenu.setOnMenuItemClickListener(item -> {
            // 菜单项点击事件的处理逻辑

            if (item.getItemId() == R.id.exec) {
                sendMsg(udpCommandModel);
                return true;
            } else if (item.getItemId() == R.id.update) {


                View dia_view = ViewUtils.inflateLayout(context, R.layout.dialog_add_udp);

                TextInputLayout til1 = dia_view.findViewById(R.id.til1);
                TextInputLayout til2 = dia_view.findViewById(R.id.til2);
                TextInputLayout til3 = dia_view.findViewById(R.id.til3);
                TextInputLayout til4 = dia_view.findViewById(R.id.til4);
                TextInputLayout til5 = dia_view.findViewById(R.id.til5);

                ViewUtils.setTextInputLayoutText(til1, udpCommandModel.getName());
                ViewUtils.setTextInputLayoutText(til2, udpCommandModel.getIp());
                ViewUtils.setTextInputLayoutText(til3, udpCommandModel.getPortString());
                ViewUtils.setTextInputLayoutText(til4, udpCommandModel.getContent());
                ViewUtils.setTextInputLayoutText(til5, udpCommandModel.getNote());

                Button button1 = dia_view.findViewById(R.id.outlinedButton1);

                button1.setOnClickListener(v1 -> {
                    ViewUtils.setTextInputLayoutText(til2, "255.255.255.255");
                    ViewUtils.setTextInputLayoutText(til5, "广播类型信息");
                });


                AlertDialog addDia = new BaseAlertDialogBuilder(context)
                        .setTitle("更新命令")
                        .setView(dia_view)
                        .setNeutralButton("取消", null)
                        .setPositiveButton("更新", null).show();

                addDia.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(v12 -> {

                    String name = ViewUtils.getTextInputLayoutText(til1);
                    String ip = ViewUtils.getTextInputLayoutText(til2);
                    String port = ViewUtils.getTextInputLayoutText(til3);
                    String content = ViewUtils.getTextInputLayoutText(til4);
                    String note = ViewUtils.getTextInputLayoutText(til5);

                    //非法检测
                    if (StringUtils.containsEmpty(name, ip, port, content)) {
                        DabaiUtils.showDialog(context, "各项不能为空");
                        return;
                    }
                    if (!IPUtils.isIP(ip)) {
                        DabaiUtils.showDialog(context, "非法IP地址");
                        return;
                    }
                    if (!IPUtils.isPort(port)) {
                        DabaiUtils.showDialog(context, "非法端口");
                        return;
                    }

                    udpCommandModel.setName(name);
                    udpCommandModel.setIp(ip);
                    udpCommandModel.setPort(Integer.parseInt(port));
                    udpCommandModel.setContent(content);
                    udpCommandModel.setNote(note);


                    int row = SQLiteDatabaseHelper.updateById(db, udpCommandModel.getId(), udpCommandModel);

                    if (row != 0) {

                        udpAdapter.setData(position, udpCommandModel);
                        udpAdapter.notifyItemChanged(position);

                        Toasty.success(this, "更新成功", Toast.LENGTH_SHORT, true).show();
                    } else {
                        Toasty.error(this, "更新失败", Toast.LENGTH_SHORT, true).show();
                    }

                    LogUtils.appendLog(LogTagEnum.TAG_CMD_UPDATE, udpCommandModel.toString());
                    addDia.dismiss();

                });


                return true;
            } else if (item.getItemId() == R.id.copy) {
//todo copy

                UdpCommandModel udpCommandModel2 = new UdpCommandModel(udpCommandModel.getName(),
                        udpCommandModel.getNote(), udpCommandModel.getIp(), udpCommandModel.getPort(), udpCommandModel.getContent());

                long id = SQLiteDatabaseHelper.insertData(db, udpCommandModel2);
                udpCommandModel2.setId((int) id);

                if (id != -1) {

                    udpAdapter.addData(udpCommandModel2);
                    udpAdapter.notifyItemInserted(udpAdapter.getItemCount());

                    Toasty.success(this, "复制成功", Toast.LENGTH_SHORT, true).show();

                    // 将ScrollView滚动到底部
                    mRecyclerview1.post(() -> mRecyclerview1.smoothScrollToPosition(udpAdapter.getItemCount() - 1));

                } else {
                    Toasty.error(this, "复制失败", Toast.LENGTH_SHORT, true).show();
                }

                LogUtils.appendLog(LogTagEnum.TAG_CMD_COPY, udpCommandModel.toString());

                return true;
            } else if (item.getItemId() == R.id.dele) {
                SQLiteDatabaseHelper.delById(db, udpCommandModel.getId());
                //refreshData();
                udpAdapter.removeAt(position);
                udpAdapter.notifyItemRemoved(position);

                Toasty.success(this, "删除成功", Toast.LENGTH_SHORT, true).show();
                LogUtils.appendLog(LogTagEnum.TAG_CMD_DEL, udpCommandModel.toString());

                return true;
            } else {
                return false;
            }
        });
    }


    /**
     * 发送消息
     *
     * @param udpCommandModel udp命令模型
     */
    private void sendMsg(UdpCommandModel udpCommandModel) {

        new Thread(() -> {

            try {

                defaultSendUdpManager.setIpAndPort(udpCommandModel.getIp(), udpCommandModel.getPort());
                defaultSendUdpManager.sendMsg(udpCommandModel.getContent());
                runOnUiThread(() -> Toasty.success(this, "发送成功", Toast.LENGTH_SHORT, true).show());
                LogUtils.appendLog(LogTagEnum.TAG_CMD_EXEC, udpCommandModel.toString());

            } catch (Exception e) {
                LogUtils.appendLog(LogTagEnum.TAG_CMD_EXEC, e.getMessage());

                runOnUiThread(() -> DabaiUtils.showDialog(context, e.getMessage()));
            }

        }).start();
    }


    ActivityResultLauncher<Intent> launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {

        if (result.getResultCode() == 101) {
            Intent data = result.getData();
            // 处理返回的数据
            if (data != null && data.getBooleanExtra("isRef", false)) {
                refreshData();
                // 将ScrollView滚动到底部
                mRecyclerview1.post(() -> mRecyclerview1.smoothScrollToPosition(udpAdapter.getItemCount() - 1));
            }
        }

        if (result.getResultCode() == 102) {
            Intent data = result.getData();
            // 处理返回的数据
            if (data != null && data.getBooleanExtra("isDel", false)) {
                refreshData();
            }
        }


    });


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.app_setting) {

            Intent intent = new Intent(this, SettingsActivity.class);
            launcher.launch(intent);

            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //设置返回按钮：不应该退出程序---而是返回桌面
    //复写onKeyDown事件
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 初始化其他视图
     */
    private void initOtherViews() {
        //页面1的控件
        mIpaddress1 = page1_root_view.findViewById(R.id.ipAddress1);
        mIpaddress2 = page2_root_view.findViewById(R.id.ipAddress2);
        mRecyclerview1 = page1_root_view.findViewById(R.id.recyclerView1);
        mRecyclerview2 = page2_root_view.findViewById(R.id.recyclerView2);

        defaultTextPort = page2_root_view.findViewById(R.id.textView_port);
        defaultTextIp = page2_root_view.findViewById(R.id.textView_ip);
        defaultTextContent = page2_root_view.findViewById(R.id.textView_content);
        defaultMode = page2_root_view.findViewById(R.id.chip4);


        //公共控件
        mBottomNavigation = findViewById(R.id.bottom_navigation);
        mFloatingActionButton1 = findViewById(R.id.floating_action_button);
        mFloatingActionButton2 = findViewById(R.id.floating_action_button2);

        setFloatButtonVisibility();

        mRecyclerview1.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {

                if (dy > 0) {
                    // 向上滚动，隐藏FloatingActionButton
                    mFloatingActionButton1.hide();
                } else if (dy < 0) {
                    // 向下滚动，显示FloatingActionButton
                    mFloatingActionButton1.show();
                }
            }
        });
        mRecyclerview2.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {

                if (dy > 0) {
                    // 向上滚动，隐藏FloatingActionButton
                    mFloatingActionButton2.hide();
                } else if (dy < 0) {
                    // 向下滚动，显示FloatingActionButton
                    mFloatingActionButton2.show();
                }
            }
        });


    }

    private void setFloatButtonVisibility() {

        if (viewPager.getCurrentItem() == 0) {
            mFloatingActionButton1.show();
            mFloatingActionButton2.hide();
        } else {
            mFloatingActionButton1.hide();
            mFloatingActionButton2.show();
        }

    }
}

/*
shi山代码 谁写的？
谁家小孩
*/
